/*
 * Copyright (c) 2010 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.fdaoud.rayures.extension;

import net.sourceforge.stripes.controller.NameBasedActionResolver;

/**
 * A custom {@link net.sourceforge.stripes.controller.ActionResolver} that is meant to be used with
 * the {@link net.sourceforge.stripes.controller.DynamicMappingFilter} and clean URLs, by providing
 * a <i>default URL binding</i> of action beans without a suffix, and lowercase letters separated by
 * underscores.
 *
 * @author Frederic Daoud
 */
public class RayuresActionResolver extends NameBasedActionResolver {

  /**
   * Returns {@code ""}, so that URL bindings have no suffix by default, fitting well with clean
   * URLs provided by the {@link net.sourceforge.stripes.controller.DynamicMappingFilter}.
   */
  @Override
  protected String getBindingSuffix() {
    return "";
  }

  /**
   * Converts the URL binding to lowercase with words separated by underscores.
   * For example, {@code /admin/UserLogin} becomes {@code /admin/user_login}.
   */
  @Override
  protected String getUrlBinding(String actionBeanName) {
    String result = super.getUrlBinding(actionBeanName);
    result = convertToLowerCaseWithUnderscores(result);
    return result;
  }

  private String convertToLowerCaseWithUnderscores(String string) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0, t = string.length(); i < t; i++) {
      char ch = string.charAt(i);
      if (Character.isUpperCase(ch)) {
        ch = Character.toLowerCase(ch);
        if (i > 0 && string.charAt(i - 1) != '/') {
          builder.append('_');
        }
      }
      builder.append(ch);
    }
    return builder.toString();
  }
}
